package cn.itcast.bos.system.action;

import java.util.List;
import java.util.UUID;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.base.action.BaseAction;
import cn.itcast.bos.domain.security.Menu;
import cn.itcast.bos.domain.security.User;
import cn.itcast.bos.system.service.UserService;

@ParentPackage("json-default")
@Controller
@Namespace("/")
@Scope("prototype")
public class UserAction extends BaseAction<User>{
	private Integer[] roleIds;
	public void setRoleIds(Integer[] roleIds) {
		this.roleIds = roleIds;
	}
	@Autowired
	private HashedCredentialsMatcher hashedCredentialsMatcher;
	
	@Autowired
	private UserService userservice;
	@Action(value="login",results={@Result(name="success",location="index.html",type="redirect"),@Result(
			name="login",location="login.html",type="redirect")})
	public String login(){
		Subject subject = SecurityUtils.getSubject();
		AuthenticationToken authenticationToken=new UsernamePasswordToken(t.getUsername()
				,t.getPassword());
		try {
			subject.login(authenticationToken);
			return SUCCESS;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return LOGIN;
		}
	}
	
	@Action(value="loginout",results={@Result(name="success",location="login.html",
			type="redirect")})
	public String loginout(){
		SecurityUtils.getSubject().logout();
		return SUCCESS;
	}
	
	@Action(value="show_user",results={@Result(name="success",type="json")})
	public String show(){
		List<User> users=userservice.show();
		ServletActionContext.getContext().getValueStack().push(users);
		return SUCCESS;
	}
	
	@Action(value="add_user")
	public String add(){
		String salt = UUID.randomUUID().toString();
		SimpleHash hash=new SimpleHash(hashedCredentialsMatcher
				.getHashAlgorithmName(), 
				t.getPassword(), salt,
				hashedCredentialsMatcher.getHashIterations());
		t.setPassword(hash.toString());
		t.setSalt(salt);
		userservice.add(t,roleIds);
		return NONE;
	}
	
	@Action(value="showMenuByUser",results={@Result(name="success",type="json")})
	public String showMenus(){
		List<Menu> menus=userservice.showMenus();
		ServletActionContext.getContext().getValueStack().push(menus);
		return SUCCESS;
	}
}
